<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Customers extends Model
{

    // 表名
    protected $name = 'kuyou_customers';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->field("id,customer_code,customertype_id,customerlevel_id,connet_name,customer_mobile,customer_phone,qq_wx_email,getgoods_address,note,customer_name,need_receive_account,receive_account,opening_prepayment,identification,deposit_bank,bank_number,staff_member_id,customer_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->field("id,customer_code,customertype_id,customerlevel_id,connet_name,customer_mobile,customer_phone,qq_wx_email,getgoods_address,note,customer_name,need_receive_account,receive_account,opening_prepayment,identification,deposit_bank,bank_number,staff_member_id,customer_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customertype_name'] = (new Customertype())->where(['id'=>$list_v['customertype_id']])->value('type_name');
            $list[$list_k]['customerlevel_name'] = (new Customerlevel())->where(['id'=>$list_v['customerlevel_id']])->value('name');
            $list[$list_k]['staff_member_name'] = (new StaffMember())->where(['id'=>$list_v['staff_member_id']])->value('name');
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->field("id,customer_code,customertype_id,customerlevel_id,connet_name,customer_mobile,customer_phone,qq_wx_email,getgoods_address,note,customer_name,receive_account,opening_prepayment,identification,deposit_bank,bank_number,staff_member_id,customer_mobile,FROM_UNIXTIME(account_time,'%Y-%m-%d') as account_time,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,status")->find();
        if($detail){
            $detail['customertype_name'] = (new Customertype())->where(['id'=>$detail['customertype_id']])->value('type_name');
            $detail['customerlevel_name'] = (new Customerlevel())->where(['id'=>$detail['customerlevel_id']])->value('name');
            $detail['staff_member_name'] = (new StaffMember())->where(['id'=>$detail['staff_member_id']])->value('name');
            $detail['user'] = collection((new CustomersUser())->field("first_connect_name,first_connect_mobile,first_connect_phone,qq_wx_email,connect_address,is_first")->where(['sid'=>$detail['id']])->select())->toArray();
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'customer_code|编号'=>'require',
                'customer_name|名称'=>'require',
                'customerlevel_id|客户等级'=>'require|in:1,2,3,4,5',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['customer_code'],1);//验证编号是否合法
                if($status){
                    if(isset($detail['account_time']) && !empty($detail['account_time'])){
                        $detail['account_time'] = strtotime($detail['account_time']);
                    }else{
                        $detail['account_time'] = time();
                    }
                    if(isset($detail['customerlevel_id']) && !empty($detail['customerlevel_id'])){
                        $customerlevel_id = (new Customerlevel())->where(['id'=>$detail['customerlevel_id']])->value('id');
                        if(empty($customerlevel_id)){
                            return ['status'=>500,'msg'=>'客户等级不存在'];
                        }
                    }
                    if(isset($detail['customertype_id']) && !empty($detail['customertype_id'])){
                        $customertype_id = (new Customertype())->where(['id'=>$detail['customertype_id']])->value('id');
                        if(empty($customertype_id)){
                            return ['status'=>500,'msg'=>'客户类别不存在'];
                        }
                    }
                    $user = (array)json_decode($detail['user'], true);
                    $default = '';
                    foreach ($user as $user_k=>$user_v){
                        if(!is_array($user_v)){
                            return ['status'=>500,'msg'=>'联系人数据格式错误'];
                        }
                        if(isset($user_v['first_connect_name']) && !empty($user_v['first_connect_name']) && isset($user_v['first_connect_mobile']) && !empty($user_v['first_connect_mobile'])){
                            if($user_v['is_first']==1 && $default!==''){
                                return ['status'=>500,'msg'=>'只能选择一个首要联系人'];
                            }
                            if($user_v['is_first']==1){
                                $default = $user_k;
                            }
                        }else{
                            unset($user[$user_k]);
                        }
                    }
                    $default = $default===''?0:$default;
                    $user[$default]['is_first'] = 1;
                    $detail['connet_name'] = $user[$default]['first_connect_name'];
                    $detail['customer_mobile'] = isset($user[$default]['first_connect_mobile'])?$user[$default]['first_connect_mobile']:'';
                    $detail['customer_phone'] = isset($user[$default]['first_connect_phone'])?$user[$default]['first_connect_phone']:'';
                    $detail['qq_wx_email'] = isset($user[$default]['qq_wx_email'])?$user[$default]['qq_wx_email']:'';
                    $detail['getgoods_address'] = isset($user[$default]['connect_address'])?$user[$default]['connect_address']:'';
                    $detail['need_receive_account'] = round(((float)$detail['receive_account']-(float)$detail['opening_prepayment']),4);

                    $model = new Customers();
                    $row = $model->where(['customer_code'=>$detail['customer_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }
                    $res = false;
                    Db::startTrans();
                    try {
                        $res = $model->allowField(true)->save($detail);
                        $result = $model->id;

                        //插入联系人
                        foreach ($user as $user_k=>$user_v){
                            $user[$user_k]['customers_code'] = trim($detail['customer_code']);
                            $user[$user_k]['sid'] = $result;
                        }
                        (new CustomersUser)->allowField(true)->saveAll($user);

                        //插入期初应收/预收
                        $detail['need_receive_account'] = ((float)$detail['receive_account']-(float)$detail['opening_prepayment']);
                        $business_type = 5;
                        if($detail['need_receive_account']>0){//应收
                            (new WriteoffSource)->allowField(true)->save([
                                'purchase_type' => 5,
                                'type' => 3,
                                'customers_id' => $result,
                                'purchase_code' => $detail['customer_code'],
                                'purchase_time' => $detail['account_time'],
                                'price' => $detail['need_receive_account'],
                                'write_off' => $detail['need_receive_account'],
                                'remark' => $detail['note'],
                            ]);
                        }else if($detail['need_receive_account']<0){//预收
                            (new WriteoffSource)->allowField(true)->save([
                                'purchase_type' => 6,
                                'type' => 3,
                                'customers_id' => $result,
                                'purchase_code' => $detail['customer_code'],
                                'purchase_time' => $detail['account_time'],
                                'price' => -$detail['need_receive_account'],
                                'write_off' => -$detail['need_receive_account'],
                                'remark' => $detail['note'],
                            ]);
                            $business_type = 6;
                        }
                        (new SalesPaymentLog)->allowField(true)->save([
                            'customers_id' => $result,
                            'business_type' => $business_type,
                            'bill_time' => $detail['account_time'],
                            'bill_code' => $detail['customer_code'],
                            'give_money' => $detail['need_receive_account'],
                        ]);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($res){
                        return ['status'=>200,'msg'=>$result];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'customer_code|编号'=>'require',
                'customer_name|名称'=>'require',
                'customerlevel_id|客户等级'=>'require|in:1,2,3,4,5',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['customer_code'],1);//验证编号是否合法
                if($status){
                    if(isset($detail['account_time']) && !empty($detail['account_time'])){
                        $detail['account_time'] = strtotime($detail['account_time']);
                    }else{
                        $detail['account_time'] = time();
                    }
                    if(isset($detail['customerlevel_id']) && !empty($detail['customerlevel_id'])){
                        $customerlevel_id = (new Customerlevel())->where(['id'=>$detail['customerlevel_id']])->value('id');
                        if(empty($customerlevel_id)){
                            return ['status'=>500,'msg'=>'客户等级不存在'];
                        }
                    }
                    if(isset($detail['customertype_id']) && !empty($detail['customertype_id'])){
                        $customertype_id = (new Customertype())->where(['id'=>$detail['customertype_id']])->value('id');
                        if(empty($customertype_id)){
                            return ['status'=>500,'msg'=>'客户类别不存在'];
                        }
                    }
                    $user = (array)json_decode($detail['user'], true);
                    $default = '';
                    foreach ($user as $user_k=>$user_v){
                        if(!is_array($user_v)){
                            return ['status'=>500,'msg'=>'联系人数据格式错误'];
                        }
                        if(isset($user_v['first_connect_name']) && !empty($user_v['first_connect_name']) && isset($user_v['first_connect_mobile']) && !empty($user_v['first_connect_mobile'])){
                            if($user_v['is_first']==1 && $default!==''){
                                return ['status'=>500,'msg'=>'只能选择一个首要联系人'];
                            }
                            if($user_v['is_first']==1){
                                $default = $user_k;
                            }
                        }else{
                            unset($user[$user_k]);
                        }
                    }
                    $default = $default===''?0:$default;
                    $user[$default]['is_first'] = 1;
                    $detail['connet_name'] = $user[$default]['first_connect_name'];
                    $detail['customer_mobile'] = isset($user[$default]['first_connect_mobile'])?$user[$default]['first_connect_mobile']:'';
                    $detail['customer_phone'] = isset($user[$default]['first_connect_phone'])?$user[$default]['first_connect_phone']:'';
                    $detail['qq_wx_email'] = isset($user[$default]['qq_wx_email'])?$user[$default]['qq_wx_email']:'';
                    $detail['getgoods_address'] = isset($user[$default]['connect_address'])?$user[$default]['connect_address']:'';
                    $detail['need_receive_account'] = round(((float)$detail['receive_account']-(float)$detail['opening_prepayment']),4);

                    $model = new Customers();
                    $row = $model->where(['customer_code'=>$detail['customer_code'],'id'=>['<>',$detail['id']]])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }

                    $row = $model->get($detail['id']);
                    if($row){

                        $WriteoffSource = Db::name('kuyou_writeoff_source')->where(['customers_id'=>$row['id'],'type'=>3])->value('price');
                        if(((float)$row['receive_account']-(float)$row['opening_prepayment'])==$WriteoffSource && ((float)$row['receive_account']-(float)$row['opening_prepayment'])!=((float)$detail['receive_account']-(float)$detail['opening_prepayment'])){
                            $order = Db::name('kuyou_writeoff')->where(['customers_id|customers_out_id|customers_enter_id'=>$row['id']])->find();
                            if($order){
                                return ['status'=>400,'msg'=>'已关联核销单，不可编辑金额'];
                            }
                        }

                        $ids = $row['id'];
                        $res = false;
                        Db::startTrans();
                        try {
                            (new CustomersUser)->where(['sid'=>$ids])->delete();

                            $res = $row->allowField(true)->save($detail);

                            //插入联系人
                            foreach ($user as $user_k=>$user_v){
                                $user[$user_k]['customers_code'] = trim($detail['customer_code']);
                                $user[$user_k]['sid'] = $ids;
                            }
                            (new CustomersUser)->allowField(true)->saveAll($user);

                            //插入期初应收/预收
                            $WriteoffSource = Db::name('kuyou_writeoff_source')->where(['customers_id'=>$ids,'type'=>3])->find();
                            $PaymentLog = Db::name('kuyou_sales_payment_log')->where(['bill_code'=>$row['customer_code'],'business_type'=>['in',[5,6]]])->find();
                            $detail['need_receive_account'] = ((float)$detail['receive_account']-(float)$detail['opening_prepayment']);
                            if($WriteoffSource){
                                $business_type = 5;
                                if($detail['need_receive_account']>0){//应收
                                    Db::name('kuyou_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                        'purchase_type' => 5,
                                        'type' => 3,
                                        'customers_id' => $ids,
                                        'purchase_code' => $detail['customer_code'],
                                        'purchase_time' => $detail['account_time'],
                                        'price' => $detail['need_receive_account'],
                                        'write_off' => $detail['need_receive_account'],
                                        'remark' => $detail['note'],
                                    ]);
                                }else if($detail['need_receive_account']<0){//预收
                                    Db::name('kuyou_writeoff_source')->where(['id'=>$WriteoffSource['id']])->update([
                                        'purchase_type' => 6,
                                        'type' => 3,
                                        'customers_id' => $ids,
                                        'purchase_code' => $detail['customer_code'],
                                        'purchase_time' => $detail['account_time'],
                                        'price' => -$detail['need_receive_account'],
                                        'write_off' => -$detail['need_receive_account'],
                                        'remark' => $detail['note'],
                                    ]);
                                    $business_type = 6;
                                }
                                Db::name('kuyou_sales_payment_log')->where(['id'=>$PaymentLog['id']])->update([
                                    'customers_id' => $ids,
                                    'business_type' => $business_type,
                                    'bill_time' => $detail['account_time'],
                                    'bill_code' => $detail['customer_code'],
                                    'give_money' => $detail['need_receive_account'],
                                ]);
                            }else{
                                $business_type = 5;
                                if($detail['need_receive_account']>0){//应收
                                    Db::name('kuyou_writeoff_source')->insert([
                                        'purchase_type' => 5,
                                        'type' => 3,
                                        'customers_id' => $ids,
                                        'purchase_code' => $detail['customer_code'],
                                        'purchase_time' => $detail['account_time'],
                                        'price' => $detail['need_receive_account'],
                                        'write_off' => $detail['need_receive_account'],
                                        'remark' => $detail['note'],
                                    ]);
                                }else if($detail['need_receive_account']<0){//预收
                                    Db::name('kuyou_writeoff_source')->insert([
                                        'purchase_type' => 6,
                                        'type' => 3,
                                        'customers_id' => $ids,
                                        'purchase_code' => $detail['customer_code'],
                                        'purchase_time' => $detail['account_time'],
                                        'price' => -$detail['need_receive_account'],
                                        'write_off' => -$detail['need_receive_account'],
                                        'remark' => $detail['note'],
                                    ]);
                                    $business_type = 6;
                                }
                                Db::name('kuyou_sales_payment_log')->insert([
                                    'customers_id' => $ids,
                                    'business_type' => $business_type,
                                    'bill_time' => $detail['account_time'],
                                    'bill_code' => $detail['customer_code'],
                                    'give_money' => $detail['need_receive_account'],
                                ]);
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $ids = explode(',',$id);
            $code = (new Customers())->where(['id'=>['in',$id]])->column('customer_code');
            foreach ($ids as $k=>$v){
                $customer = self::getDetail($v);
                $customer_name = isset($customer['customer_name'])?$customer['customer_name']:'客户';
                $order_info = (new SalesOrderInfo())->where(['customers_id'=>$v])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$customer_name.'已有销货订单，不可删除'];
                }
                $order_info = (new GoodsSalesInfo())->where(['customers_id'=>$v])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$customer_name.'已有销货单，不可删除'];
                }
                $order_info = (new SalesExchangeInfo())->where(['customers_id'=>$v])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$customer_name.'已有销货退货单，不可删除'];
                }
                $order_info = (new Warehouse())->where(['customers_id'=>$v])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$customer_name.'已有其他入库单，不可删除'];
                }
                $order_info = (new Writeoff())->where(['customers_id|customers_out_id|customers_enter_id'=>$v])->field('id')->find();
                if(!empty($order_info)){
                    return ['status'=>500,'msg'=>$customer_name.'已有核销单，不可删除'];
                }
            }
            Db::startTrans();
            try {
                $res = (new Customers())->where(['id'=>['in',$id]])->delete();
                (new CustomersUser)->where(['sid'=>['in',$id]])->delete();
                (new WriteoffSource)->where(['customers_id'=>['in',$id],'type'=>3])->delete();
                (new SalesPaymentLog)->where(['bill_code'=>['in',$code],'business_type'=>['in',[5,6]]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 导入
     * @param array $add,$edit
     * @return array
     */
    public static function import($add,$edit){
        if(empty($add) && empty($edit)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $model = new Customers();

            Db::startTrans();
            try {
                foreach ($add as $add_k=>$detail){
                    $res = $model->allowField(true)->save($detail);
                    $result = $model->id;

                    $user = $detail['userlist'];
                    //插入联系人
                    foreach ($user as $user_k=>$user_v){
                        $user[$user_k]['customers_code'] = trim($detail['customer_code']);
                        $user[$user_k]['sid'] = $result;
                    }
                    (new CustomersUser)->allowField(true)->saveAll($user);

                    //插入期初应收/预收
                    $business_type = 5;
                    if($detail['need_receive_account']>0){//应收
                        (new WriteoffSource)->allowField(true)->save([
                            'purchase_type' => 5,
                            'type' => 3,
                            'customers_id' => $result,
                            'purchase_code' => $detail['customer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_receive_account'],
                            'write_off' => $detail['need_receive_account'],
                            'remark' => $detail['note'],
                        ]);
                    }else if($detail['need_receive_account']<0){//预收
                        (new WriteoffSource)->allowField(true)->save([
                            'purchase_type' => 6,
                            'type' => 3,
                            'customers_id' => $result,
                            'purchase_code' => $detail['customer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_receive_account'],
                            'write_off' => $detail['need_receive_account'],
                            'remark' => $detail['note'],
                        ]);
                        $business_type = 6;
                    }
                    (new SalesPaymentLog)->allowField(true)->save([
                        'customers_id' => $result,
                        'business_type' => $business_type,
                        'bill_time' => $detail['account_time'],
                        'bill_code' => $detail['customer_code'],
                        'give_money' => $detail['need_receive_account'],
                    ]);
                }
                foreach ($edit as $edit_k=>$detail){
                    $row = $model->get($detail['id']);
                    $ids = $detail['id'];
                    (new CustomersUser)->where(['sid'=>$ids])->delete();
                    (new WriteoffSource)->where(['customers_id'=>$ids,'type'=>3])->delete();
                    (new SalesPaymentLog)->where(['bill_code'=>$detail['customer_code'],'business_type'=>['in',[5,6]]])->delete();

                    $res = $row->allowField(true)->save($detail);

                    $user = $detail['userlist'];
                    //插入联系人
                    foreach ($user as $user_k=>$user_v){
                        $user[$user_k]['customers_code'] = trim($detail['customer_code']);
                        $user[$user_k]['sid'] = $ids;
                    }
                    (new CustomersUser)->allowField(true)->saveAll($user);

                    //插入期初应收/预收
                    $business_type = 5;
                    if($detail['need_receive_account']>0){//应收
                        (new WriteoffSource)->allowField(true)->save([
                            'purchase_type' => 5,
                            'type' => 3,
                            'customers_id' => $ids,
                            'purchase_code' => $detail['customer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_receive_account'],
                            'write_off' => $detail['need_receive_account'],
                            'remark' => $detail['note'],
                        ]);
                    }else if($detail['need_receive_account']<0){//预收
                        (new WriteoffSource)->allowField(true)->save([
                            'purchase_type' => 6,
                            'type' => 3,
                            'customers_id' => $ids,
                            'purchase_code' => $detail['customer_code'],
                            'purchase_time' => $detail['account_time'],
                            'price' => $detail['need_receive_account'],
                            'write_off' => $detail['need_receive_account'],
                            'remark' => $detail['note'],
                        ]);
                        $business_type = 6;
                    }
                    (new SalesPaymentLog)->allowField(true)->save([
                        'customers_id' => $ids,
                        'business_type' => $business_type,
                        'bill_time' => $detail['account_time'],
                        'bill_code' => $detail['customer_code'],
                        'give_money' => $detail['need_receive_account'],
                    ]);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            return ['status'=>200,'msg'=>'导入成功'];
        }
    }
}
